if ($('#row').length > 0) {
    row = JSON.parse($('#row').val());
} else {
    row = null;
}

window.addEventListener('keydown', function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
    }
});

var marker;

function getValue(str) {
    const selectors = [
        `#c-${str}`,
        `#c-${str}2`,
        `#c-${str}3`,
        `#c-${str}4`,
        `#h-${str}`
    ];
    for (const selector of selectors) {
        if ($(selector).length > 0) {
            return $(selector).val();
        }
    }

    return Config.admin[str] || null;
}


$(document).on("change change2", "#c-rel_type", function () {
    if ($('#c-rel_id').length > 0) {
        if ($("#c-rel_type").val() == 1) {
            if ($("#c-address_lv").length > 0) {
                $("#div-address_lv").parent("div.form-group").show();
            } else if ($("#div-class_type_css").length > 0) {
                $("#div-class_type_css,#div-class_type2_css").hide();
            } else if ($("#div-subject_lv_css").length > 0) {
                $("#div-subject_lv_css,#div-subject_lv2_css").show();
            } else if ($("#c-ocation_id2").length > 0) {
                $("#c-ocation_id2").trigger("change2");
            }

            $.ajax({
                url: "/school/school/lists",
                data: {cityId: $("#city").val(), districtId: $("#county").val()},
                type: "GET",
                success: function (data) {
                    var $school = $('#c-rel_id');
                    $school.empty();
                    $school.append('<option value="">请选择学校</option>');
                    var list = JSON.parse(data);
                    $.each(list["list"], function (index, school) {
                        $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                    });
                },
                error: function (xhr, status, error) {
                    console.error("Error fetching school list: ", error);
                }
            });
        } else if ($("#c-rel_type").val() == 2) {
            if ($("#c-address_lv").length > 0) {
                $("#div-address_lv").parent("div.form-group").hide();
            }
            if ($("#div-class_type_css").length > 0) {
                $("#div-class_type_css,#div-class_type2_css").show();
            }
            if ($("#div-subject_lv_css").length > 0) {
                $("#div-subject_lv_css,#div-subject_lv2_css").hide();
            }
            if ($("#c-ocation_id2").length > 0) {
                $("#c-ocation_id2").trigger("change2");
            }

            $.ajax({
                url: "/community/community/lists",
                data: {cityId: $("#city").val(), districtId: $("#county").val()},
                type: "GET",
                success: function (data) {
                    var $school = $('#c-rel_id');
                    $school.empty();
                    $school.append('<option value="">请选择社区</option>');
                    var list = JSON.parse(data);
                    $.each(list["list"], function (index, school) {
                        $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                    });
                },
                error: function (xhr, status, error) {
                    console.error("Error fetching school list: ", error);
                }
            });
        }
    }
});

$("#c-rel_type").trigger("change2", function () {
    $("#c-rel_id").trigger("change2", function () {
        if ($("#c-address_lv").length > 0) {
            //$("#c-pid").val(row.pid);
        }
    });
});


$(document).on("change2 change", "#c-rel_id", function () {
    if ($('#c-pid').length > 0) {
        var $school = $('#c-pid');
        $school.empty();
        $school.append('<option value="">请选择父级</option>');
        $.ajax({
            url: "/addresslv/addresslv/lists",
            data: {relType: $("#c-rel_type").val(), relId: $("#c-rel_id").val(), cityId: $("#c-city_id").val()},
            type: "GET",
            success: function (data) {
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    }
    if ($('#c-address_lv').length > 0) {
        var $school = $('#c-address_lv');
        $school.empty();
        $school.append('<option value="">请选择父级</option>');
        $.ajax({
            url: "/addresslv/addresslv/lists",
            data: {relType: $("#c-rel_type").val(), relId: $("#c-rel_id").val(), cityId: $("#c-city_id").val()},
            type: "GET",
            success: function (data) {
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    }

    if ($('#c-school_id').length > 0) {
        if ($("#c-community_id").length > 0 && $('#c-rel_type').val() == 1) {
            $("#c-community_id").parents("div.form-group").hide();
        }
        if ($("#c-school_id").length > 0 && $('#c-rel_type').val() == 1) {
            $("#c-school_id").parents("div.form-group").show();
        }
        if ($('#c-rel_type').length > 0 && $('#c-rel_type').val() == 1) {
            $('#c-school_id').val($('#c-rel_id').val());
        }
    }
    if ($('#c-community_id').length > 0) {
        if ($("#c-community_id").length > 0 && $('#c-rel_type').val() == 2) {
            $("#c-community_id").parents("div.form-group").show();
        }
        if ($("#c-school_id").length > 0 && $('#c-rel_type').val() == 2) {
            $("#c-school_id").parents("div.form-group").hide();
        }
        if ($('#c-rel_type').length > 0 && $('#c-rel_type').val() == 2) {
            $('#c-community_id').val($('#c-rel_id').val());
        }
    }

});


if ($('select[name="row[province_id]"]').length > 0) {
    var $province = $('select[name="row[province_id]"]');
    $.getJSON('/cityarea/cityarea/getAreas', {level: 1}, function (provinces) {
        $province.append('<option value="">请选择省份</option>');
        $.each(provinces, function (index, province) {
            $province.append('<option value="' + province.id + '">' + province.name + '</option>');
        });
        if (row && $("#province_id").length > 0) {
            $("#province_id").val(row.province_id);
        } else {
            $("#province_id").val(0);
        }
        // 触发加载市级数据
        var $city = $('#city');
        $province.change(function () {
            var provinceId = $(this).val();
            $.getJSON('/cityarea/cityarea/getAreas?XDEBUG_SESSION_START=54325', {
                level: 2,
                parent_id: provinceId
            }, function (cities) {
                $city.empty();
                $city.append('<option value="">请选择城市</option>');
                $city.append('<option value="0">区级</option>');
                $.each(cities, function (index, city) {
                    $city.append('<option value="' + city.id + '">' + city.name + '</option>');
                });
                if (row && $("#city_id").length > 0) {
                    $("#city_id").val(row.city_id);
                } else {
                    $("#city_id").val(2);
                }
                // 触发加载县级数据
                $city.change(function () {
                    var cityId = $(this).val();
                    if (cityId == 0) {
                        $("#county").hide();
                        $county.empty();
                        return;
                    } else {
                        $("#county").show();
                    }
                    $.getJSON('/cityarea/cityarea/getAreas?XDEBUG_SESSION_START=54325', {
                        level: 3,
                        parent_id: cityId
                    }, function (counties) {
                        var $county = $('#county');
                        $county.empty();
                        $county.append('<option value="-1">请选择城区（县）</option>');
                        $county.append('<option value="0">市级</option>');
                        $.each(counties, function (index, county) {
                            $county.append('<option value="' + county.id + '">' + county.name + '</option>');
                        });

                        if (row && $("#county").length > 0) {
                            $("#county").val(row.district_id);
                        } else {
                            $county.val(0);
                        }
                        if ($('#c-latitude').length > 0) {
                            updateMap(1);
                        }
                        $county.change(function () {
                            if ($('#c-latitude').length > 0) {
                                updateMap(2);
                            }
                        });
                        $("#c-rel_type").trigger("change");
                    });
                    $("#c-rel_type").trigger("change");
                });
                $city.val(2);
                $city.trigger("change");
            });
        });
        $province.val(1);
        $province.trigger("change");
    });
    $province.trigger("change");
}

$(document).on("change change2", "#c-school_id,#c-school_id_tree", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        let url="";
        if(e.target.id == "c-school_id_tree"){
            url="/school/school/lists2?XDEBUG_SESSION_START=54354";
        }else{
            url="/school/school/lists?XDEBUG_SESSION_START=54354";
        }
        $.ajax({
            url: url,
            data: {cityId: Config.admin['city_id'], school_id: Config.admin['school_id']},
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if ($("#c-addresslv_id").length > 0) {
                    $("#c-addresslv_id").trigger("change2");
                }
                if ($("#c-subject_lv").length > 0) {
                    $("#c-subject_lv").trigger("change2");
                }

                if (row) {
                    that.val(row.school_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
        if ($("#c-addresslv_id3").length > 0) {
            $("#c-addresslv_id3").trigger("change3");
        }
        if ($("#c-subject_lv").length > 0) {
            $("#c-subject_lv").trigger("change2");
        }
    }


    if ($("#c-addresslv_id").length > 0) {
        $("#c-addresslv_id").trigger("change2");
    }
    if ($("#c-addresslv_id3").length > 0) {
        $("#c-addresslv_id").trigger("change3");
    }


});


$(document).on("change change2", "#c-community_id", function (e) {
    if (e.type == "change2") {
        $.ajax({
            url: "/community/community/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: Config.admin['city_id'], school_id: Config.admin['school_id']},
            type: "GET",
            success: function (data) {
                var $school = $('#c-community_id');
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if ($("#c-addresslv_id").length > 0) {
                    $("#c-addresslv_id").trigger("change2");
                }
                if (row) {
                    that.val(row.shool_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
    }
    if ($("#c-addresslv_id").length > 0) {
        $("#c-addresslv_id").trigger("change2");
    }
});

$(document).on("change change2 change3", "#c-subject_lv,#c-subject_lv2,#c-subject_lv2,#c-subjecct-lv3-pid", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    if($("#c-school_id_tree").length > 0){
        addressLv = $("#c-school_id_tree").val();
    }
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学科层级</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('subject_lv')) {
                        that.val(row.subject_lv);
                    } else if (row.hasOwnProperty('subjectlv')) {
                        that.val(row.subjectlv);
                    }
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else if (e.type == "change3") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择学科层级</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('pid')) {
                        that.val(row.pid);
                    } else if (row.hasOwnProperty('subjectlv')) {
                        that.val(row.subjectlv);
                    }
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
    }
});


$(document).on("change change2", "#c-class_type", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/subjectlv/subjectlv/class_type?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择课程类型</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('class_type')) {
                        that.val(row.class_type);
                    } else if (row.hasOwnProperty('class_type')) {
                        that.val(row.class_type);
                    }
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    }else {

    }
});

$(document).on("change change2", "#c-classes_type", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let addressLv = getValue("addresslv_id");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/classes/classes/classes_type?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                $school.empty();
                $school.append('<option value="">请选择班级类型</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('classes_type')) {
                        that.val(row.classes_type);
                    } else if (row.hasOwnProperty('classes_type')) {
                        that.val(row.classes_type);
                    }
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    }else {

    }
});

$(document).on("change change2 change3 change4", "#c-address_lv,#c-addresslv_id,#c-address_lv3,#c-addresslv_id3,#c-addresslv_id4,#c-address_lv_pid", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let relType = getValue("rel_type");
    let relId = getValue("rel_id");
    let addressLv = getValue("addresslv_id");
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/addresslv/addresslv/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, relType: relType, relId: relId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                var disabled = "";
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + ' parent="' + school.parent + '" level="' + school.level + '">' + school.name + '</option>');
                });
                if ($("#province_id").length > 0) {
                    $("#province_id").val(school.province_id);
                }
                // if ($("#c-city_id").length > 0) {
                //     $("#c-city_id").val(school.city_id);
                // }
                // if ($("#c-district_id").length > 0) {
                //     $("#c-district_id").val(school.district_id);
                // }
                if ($("#c-addresslv_id3").length > 0) {
                    $("#c-addresslv_id3").val(school.addresslv_id);
                }
                if (row) {
                    if (row.hasOwnProperty('addresslv_id')) {
                        that.val(row.addresslv_id);
                    } else if (row.hasOwnProperty('address_lv')) {
                        that.val(row.address_lv);
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }

            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else if (e.type == "change3") {
        $.ajax({
            url: "/addresslv/addresslv/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, relType: relType, relId: relId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                var disabled = "";
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '"' + disabled + ' parent="' + school.parent + '" level="' + school.level + '">' + school.name + '</option>');
                });
                if ($("#province_id").length > 0) {
                    $("#province_id").val(school.province_id);
                }
                if ($("#c-city_id").length > 0) {
                    $("#c-city_id").val(school.city_id);
                }
                if ($("#c-district_id").length > 0) {
                    $("#c-district_id").val(school.district_id);
                }
                if ($("#c-subjecct-lv3-pid").length > 0) {
                    $("#c-subjecct-lv3-pid").trigger("change3");
                }
                if (row) {
                    that.val(row.address_lv);
                    if ($("#c-address_lv_octionlevel").length > 0) {
                        $("#c-address_lv_octionlevel").val(row.address_lv_octionlevel);
                    }
                    if ($("#c-pid").length > 0) {
                        $("#c-pid").val(row.pid);
                    }
                }

                if ($("#c-address_lv_octionlevel").length > 0) {
                    //$("#c-address_lv_octionlevel").removeClass("readonly-select");
                    if ($("#c-ocation_pid").length > 0) {
                        level = $("#c-ocation_pid option:selected").attr("level");
                        $("#c-address_lv_octionlevel").find("option").each(function () {
                            if ($(this).attr("value") < level + 1) {
                                $(this).hide();
                            }
                        });
                    }

                    if ($("#c-address_lv_octionlevel").val() == 1) {
                        $("#c-starttime,#c-endtime").closest("div.form-group").hide();
                        $("#c-entvirt").closest("div.form-group").hide();
                    } else if ($("#c-address_lv_octionlevel").val() > 1) {
                        $("#c-starttime,#c-endtime").closest("div.form-group").show();
                    }
                    if ($("#c-address_lv_octionlevel").val() == 1) {
                        $("#div-entvirt").closest("div.form-group").hide();
                    } else {
                        $("#div-entvirt").closest("div.form-group").show();
                    }
                    if ($("#c-address_lv_octionlevel").val() >= 2) {
                        $("#div-ocation_type").closest("div.form-group").show();
                    } else {
                        $("#div-ocation_type").closest("div.form-group").hide();
                    }


                    //$("#c-address_lv_octionlevel").addClass("readonly-select");//pointer-events: none

                    //$("#c-ocation_pid").removeClass("readonly-select");
                }
                if (row) {
                    that.val(row.address_lv);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }

            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else if (e.type == "change4") {
        $.ajax({
            url: "/addresslv/addresslv/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: cityId, school_id: schoolId, relType: relType, relId: relId, address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = that;
                var disabled = "";
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);

                $.each(list["list"], function (index, school) {
                    disabled = (school.level > 1) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if ($("#province_id").length > 0) {
                    $("#province_id").val(school.province_id);
                }
                if ($("#c-city_id").length > 0) {
                    $("#c-city_id").val(school.city_id);
                }
                if ($("#c-district_id").length > 0) {
                    $("#c-district_id").val(school.district_id);
                }
                if ($("#c-subjecct-lv3-pid").length > 0) {
                    $("#c-subjecct-lv3-pid").trigger("change3");
                }

                if (row) {
                    if (/_pid/.test(that.attr("id"))) {
                        that.val(row.pid);
                    }
                    if (row.hasOwnProperty('addresslv_id')) {
                        that.val(row.addresslv_id);
                    } else if (row.hasOwnProperty('address_lv')) {
                        that.val(row.address_lv);
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }

            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {
        if ($("#c-pid").length > 0) {
            $("#c-pid").trigger("change2");
        }
        if ($("#c-ocation_id").length > 0) {
            $("#c-ocation_id").trigger("change2");
        }

        if ($("#c-subject_lv").length > 0) {
            $("#c-subject_lv").trigger("change2");
        }

        if ($("#c-subjecct-lv3-pid").length > 0) {
            $("#c-subjecct-lv3-pid").trigger("change3");
        }

        if ($("#c-address_lv_octionlevel").length > 0) {
            if ($("#c-ocation_pid").length > 0) {
                level = $("#c-ocation_pid option:selected").attr("level");
                $("#c-address_lv_octionlevel").find("option").each(function () {
                    if ($(this).attr("value") < level + 1) {
                        $(this).hide();
                    }
                });
            }

            //$("#c-address_lv_octionlevel").removeClass("readonly-select");
            $("#c-address_lv_octionlevel").val($("select[name='row[address_lv]'] option:selected").attr("level") + 1);
            if ($("#c-address_lv_octionlevel").val() == 1) {
                $("#c-starttime,#c-endtime").closest("div.form-group").hide();
            } else if ($("#c-address_lv_octionlevel").val() > 1) {
                $("#c-starttime,#c-endtime").closest("div.form-group").show();
            }
            if ($("#c-address_lv_octionlevel").val() == 1) {
                $("#div-entvirt").closest("div.form-group").hide();
            } else {
                $("#div-entvirt").closest("div.form-group").show();
            }
            //$("#c-address_lv_octionlevel").addClass("readonly-select");//pointer-events: none
            //$("#c-ocation_pid").removeClass("readonly-select");
            // let pid=$("select[name='row[address_lv]'] option:selected").attr("parent");
            // $("#c-ocation_pid").find("option").each(function(){
            //     if($(this).attr("value")==pid){
            //         $("#c-ocation_pid").val($(this).attr("value"));
            //         //$("#c-ocation_pid").addClass("readonly-select");
            //         return false;
            //     }
            // });

            if ($("#c-address_lv_octionlevel").val() >= 2) {
                $("#div-ocation_type").closest("div.form-group").show();
            } else {
                $("#div-ocation_type").closest("div.form-group").hide();
            }
        }
    }
});

$(document).on("change change2,change3", "#c-pid,#c-subjecct-lv3-pid", function (e) {
    let cityId = getValue("city_id");
    let schoolId = getValue("school_id");
    let relType = getValue("rel_type");
    let relId = getValue("rel_id");
    let addressLv = getValue("address_lv");
    let that = $this;
    if (e.type == "change2") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=54354",
            data: {cityId: Config.admin['city_id'], school_id: $("#c-school_id").val(), address_lv: addressLv},
            type: "GET",
            success: function (data) {
                var $school = $("#c-pid");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild) ? " disabled  class='disabled'" : "";
                    $school.append('<option value="' + school.id + '"' + disabled + '>' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.pid);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else if (e.type == "change3") {
        $.ajax({
            url: "/subjectlv/subjectlv/lists?XDEBUG_SESSION_START=11111",
            data: {cityId: Config.admin['city_id'], school_id: $("#c-school_id").val(), address_lv: addressLv},
            type: "GET",
            success: function (data) {
                alert(1);
                var $school = $("#c-pid,#c-subjecct-lv3-pid");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    if (row.hasOwnProperty('addresslv_id')) {
                        that.val(row.addresslv_id);
                    } else if (row.hasOwnProperty('address_lv')) {
                        that.val(row.address_lv);
                    }
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {

    }
});

$(document).on("change change2", "#c-ocation_id", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/ocation/ocation/lists?XDEBUG_SESSION_START=54354",
            data: {
                cityId: Config.admin['city_id'],
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
                addresslv_id: $("#c-address_lv").val()
            },
            type: "GET",
            success: function (data) {
                var $school = $("#c-ocation_id");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.ocation_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {

    }
});


$(document).on("change change2", "#c-teacher_id", function (e) {
    if (e.type == "change2") {
        $.ajax({
            url: "/user/user/lists?XDEBUG_SESSION_START=54354",
            data: {
                cityId: Config.admin['city_id'],
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
            },
            type: "GET",
            success: function (data) {
                var $school = $("#c-teacher_id");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                // if (row) {
                //     that.val(row.ocation_id);
                // } else if (that.find("option").length == 2) {
                //     that.find("option").each(function () {
                //         var value = $(this).val();
                //         if (value !== "" && value !== "0") {
                //             $(this).prop("selected", true);
                //             return false;
                //         }
                //     });
                // }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {

    }
});

//--------------------------教学点等级----------------------
$(document).on("change change2", "#c-address_lv_octionlevel", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        if (row) {
            that.val(row.address_lv);
            if ($("#c-address_lv_octionlevel").length > 0) {
                $("#c-address_lv_octionlevel").val(row.address_lv_octionlevel);
            }
            if ($("#c-pid").length > 0) {
                $("#c-pid").val(row.pid);
            }
        }
    }
    if ($("#c-address_lv_octionlevel").val() > 1) {
        $("#c-starttime,#c-endtime").closest("div.form-group").show();
    } else {
        $("#c-starttime,#c-endtime").closest("div.form-group").hide();
    }
    if ($("#c-address_lv_octionlevel").val() == 1) {
        $("#div-entvirt").closest("div.form-group").hide();
    } else {
        $("#div-entvirt").closest("div.form-group").show();
    }
    if ($("#c-address_lv_octionlevel").val() > 2) {
        $("#div-ocation_type").closest("div.form-group").show();
        $("#div-entvirt").closest("div.form-group").hide();
        $("#classroomdiv").show();
    } else {
        $("#div-ocation_type").closest("div.form-group").hide();
        $("#classroomdiv").hide();
    }

});

$(document).on("change2 change", "#c-ocation_pid", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/ocation/ocation/lists2?XDEBUG_SESSION_START=54354",
            data: {
                cityId: Config.admin['city_id'],
                relType: Config.admin['rel_type'],
                relId: Config.admin['rel_id'],
                addresslv_id: $("#c-address_lv").val()
            },
            type: "GET",
            success: function (data) {
                var $ocation = that;
                $ocation.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, ocation) {
                    //disabled = (ocation.level>1||typeof(ocation.level)=='undefined') ? " disabled  class='disabled'" : "";
                    disabled = "";
                    $ocation.append('<option value="' + ocation.id + '"' + disabled + ' parent="' + ocation.parent + '" level="' + ocation.level + '">' + ocation.name + '</option>');
                });
                if (row) {
                    that.val(row.pid);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else if (e.type == "change") {
        if ($("#c-ocation_pid").length > 0) {
            level = $("#c-ocation_pid option:selected").attr("level");
            $("#c-address_lv_octionlevel").find("option").each(function () {
                if ($(this).attr("value") <= parseInt(level)) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            $("#c-address_lv_octionlevel").val(parseInt(level) + 1);
        }
    }
});


$(document).on("change2 change", "#c-ocation_class", function (e) {
    let that = $(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/ocation/ocation/lists2?XDEBUG_SESSION_START=54354",
            data: {
                cityId: Config.admin['city_id'],
                relType: Config.admin['rel_type'],
                relId: Config.admin['rel_id'],
                addresslv_id: $("#c-address_lv").val()
            },
            type: "GET",
            success: function (data) {
                var $ocation = that;
                $ocation.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, ocation) {
                    disabled = (ocation.level < 3 || typeof (ocation.level) == 'undefined') ? " disabled  class='disabled'" : "";
                    checked = row && row.ocation_id.includes(ocation.id) ? "selected" : "";
                    $ocation.append('<option value="' + ocation.id + '"' + disabled + ' ' + checked + ' ' + ' parent="' + ocation.parent + '" level="' + ocation.level + '">' + ocation.name + '</option>');
                });
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else if (e.type == "change") {
        if ($("#c-ocation_pid").length > 0) {
            level = $("#c-ocation_class option:selected").attr("level");
            $("#c-address_lv_octionlevel").find("option").each(function () {
                if ($(this).attr("value") <= parseInt(level)) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            $("#c-address_lv_octionlevel").val(parseInt(level) + 1);
        }
    }
});

$(document).on("change change2", "#c-classes_id", function (e) {
    if (e.type == "change2") {
        $.ajax({
            url: "/classes/classes/lists2?XDEBUG_SESSION_START=54354",
            data: {
                cityId: Config.admin['city_id'],
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
                addresslv_id: $("#c-address_lv").val(),
                relType: getValue("rel_type"),
                relId: getValue("rel_id")
            },
            type: "GET",
            success: function (data) {
                var $school = $("#c-classes_id");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    disabled = (school.haschild < 3) ? " disabled  class='disabled'" : "";
                    checked = "";
                    if (row && (Array.isArray(row.classes_id) ? row.classes_id.includes(school.id) : row.classes_id == school.id)) {
                        checked = "selected";
                    }
                    $school.append('<option value="' + school.id + '"' + disabled + ' ' + checked + ' ' + ' parent="' + school.parent + '" level="' + school.level + '">' + school.name + '</option>');
                });
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {

    }
});


$(document).on("change3", "#c-rel_type", function (e) {
    var $school = $("#c-rel_type");
    $school.empty();
    $school.append('<option value="1">学校</option>');
    $school.append('<option value="2">社区</option>');
    $school.append('<option value="3">其他机构</option>');
    $("#c-rel_type").trigger("change");
});

$(document).on("change", "#group", function (e) {
    if ($("#group").val() == 8) {
        $.ajax({
            url: "/community/community/lists",
            data: {cityId: $("#city").val(), districtId: $("#county").val()},
            type: "GET",
            success: function (data) {
                var $school = $('#c-rel_id');
                $school.empty();
                $school.append('<option value="">请选择社区</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.community_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    }
    if ($("#group").val() == 2) {
        $.ajax({
            url: "/school/school/lists",
            data: {cityId: $("#city").val(), districtId: $("#county").val()},
            type: "GET",
            success: function (data) {
                var $school = $('#c-rel_id');
                $school.empty();
                $school.append('<option value="">请选择学校</option>');
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.school_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    }
});

if ($('#c-pid').length > 0 && $('#h-rel_type').length > 0 && $('#h-rel_id').length > 0) {
    var $school = $('#c-pid');
    $school.empty();
    $school.append('<option value="">请选择父级</option>');
    $.ajax({
        url: "/addresslv/addresslv/lists",
        data: {relType: $("#h-rel_type").val(), relId: $("#h-rel_id").val(), cityId: Config.cityId},
        type: "GET",
        success: function (data) {
            var list = JSON.parse(data);
            $.each(list["list"], function (index, school) {
                $school.append('<option value="' + school.id + '">' + school.name + '</option>');
            });
            if (row) {
                that.val(row.pid);
            } else if (that.find("option").length == 2) {
                that.find("option").each(function () {
                    var value = $(this).val();
                    if (value !== "" && value !== "0") {
                        $(this).prop("selected", true);
                        return false;
                    }
                });
            }
        },
        error: function (xhr, status, error) {
            console.error("Error fetching school list: ", error);
        }
    });
}

function getAddress(point) {
    var geoc = new BMap.Geocoder();
    geoc.getLocation(point, function (result) {
        if (result) {
            var address = result.address; // 获取完整的地址信息
            $("#c-address").val(address); // 将地址信息写入 #address 元素
            var addressComponents = result.addressComponents;
            $("#city option:contains('" + addressComponents.city + "')").prop("selected", true);
            $("#county option:contains('" + addressComponents.district + "')").prop("selected", true);
        }
    });
}

function updateMap(type) {
    var selectedProvince = $("#c-cityarea_id option:selected").text();
    var selectedCity = $("#city option:selected").text();
    var selectedCounty = $("#county option:selected").text();
    var point = null;
    if (type == 1 && row && row.longitude > 0) {
        point = new BMap.Point(row.longitude, row.latitude);
    } else {
        if (selectedCounty && districtCoordinates[selectedProvince] && districtCoordinates[selectedProvince][selectedCounty]) {
            point = districtCoordinates[selectedProvince][selectedCounty];
        } else if (selectedCity && districtCoordinates[selectedProvince] && districtCoordinates[selectedProvince][selectedCity]) {
            point = districtCoordinates[selectedProvince][selectedCity][selectedCounty];
        } else if (districtCoordinates[selectedProvince]) {
            point = districtCoordinates[selectedProvince][Object.keys(districtCoordinates[selectedProvince])[0]];
        }
    }
    if (point) {
        $("#c-latitude").val(point.lat);
        $("#c-longitude").val(point.lng);
    }
    if (marker) {
        map.removeOverlay(marker);
    }
    try {
        map.clearOverlays(); // 尝试清除之前的标注
        map.centerAndZoom(point, 20); // 调整缩放级别
        marker = new BMap.Marker(point);
        map.addOverlay(marker);
    } catch (error) {
        if (error instanceof TypeError && error.message.includes("Cannot read properties of undefined (reading 'clearOverlays')")) {
            // 在这里处理错误，例如记录日志或显示一个警告信息
            console.error("地图对象未正确初始化，无法清除标注。");
        } else {
            // 如果是其他类型的错误，重新抛出
            throw error;
        }
    }
}

function geocoderSearch(address) {
    var myGeo = new BMap.Geocoder();
    myGeo.getPoint(address, function (point) {
        if (point) {
            if (marker) {
                map.removeOverlay(marker);
            }
            map.clearOverlays(); // 清除之前的标注
            map.centerAndZoom(point, 15); // 调整缩放级别
            var marker = new BMap.Marker(point);
            map.addOverlay(marker);
            $("#c-latitude").val(point.lat);
            $("#c-longitude").val(point.lng);
            myGeo.getLocation(point, function (result) {
                var addressComponents = result.addressComponents;
                $("#city option:contains('" + addressComponents.city + "')").prop("selected", true);
                $("#county option:contains('" + addressComponents.district + "')").prop("selected", true);
            });
        } else {
            alert("未找到该地址，请检查输入是否正确。");
        }
    }, "中国");
}


// 获取所有的 weekday 复选框
const weekdaysCheckboxes = document.querySelectorAll('input[name="row[weekdays][]"]');
// 获取所有的 daytime 复选框
const daytimeCheckboxes = document.querySelectorAll('input[name="row[daytime][]"]');
// 获取 DisableWeekRange 下拉列表
const disableWeekRange = document.getElementById('DisableWeekRange');
// 获取 schedule-table-container 中的所有行
const scheduleTableRows = $('#schedule-table-container tr');
// 获取 DisableWeekTime 下拉列表
const disableWeekTime = $('#DisableWeekTime');

// 根据 weekday 值获取对应的文本
function getWeekdayText(weekday) {
    switch (weekday) {
        case '1':
            return '周一';
        case '2':
            return '周二';
        case '3':
            return '周三';
        case '4':
            return '周四';
        case '5':
            return '周五';
        case '6':
            return '周六';
        case '7':
            return '周日';
        default:
            return '';
    }
}

// 根据 daytime 值获取对应的文本
function getDaytimeText(daytime) {
    switch (daytime) {
        case '1':
            return '上午';
        case '2':
            return '中午';
        case '3':
            return '下午';
        case '4':
            return '晚上';
        default:
            return '';
    }
}

// 根据 lesson 值获取对应的文本
function getLessonText(lesson) {
    return `第${lesson}节课`;
}

// 生成选项并添加到下拉列表中
function addOptionsToSelect(select, options) {
    $(select).empty();
    options.forEach(option => {
        $(select).append(option);
    });
}

// 初始化 DisableWeekRange 下拉列表
function initDisableWeekRange() {
    const options = [];
    weekdaysCheckboxes.forEach(checkbox => {
        if (checkbox.checked) {

            const weekday = checkbox.value;
            const weekdayText = getWeekdayText(weekday);
            daytimeCheckboxes.forEach(checkbox2 => {
                if (checkbox2.checked) {
                    const daytime = checkbox2.value;
                    const daytimeText = getDaytimeText(daytime);
                    const option = $('<option>');
                    option.val(`${weekdayText} ${daytimeText}`);
                    option.text(`${weekdayText} ${daytimeText}`);
                    if (row && row.disable_week_range && row.disable_week_range.includes(`${weekdayText} ${daytimeText}`)) {
                        option.attr("selected", "selected");
                    }
                    options.push(option);
                }
            });
        }
    });
    if ($('#DisableWeekRange').length > 0) {
        addOptionsToSelect(disableWeekRange, options);
    }
}

// 初始化 DisableWeekTime 下拉列表
function initDisableWeekTime() {
    const options = [];
    weekdaysCheckboxes.forEach(checkbox => {
        if (checkbox.checked) {
            const weekday = checkbox.value;
            const weekdayText = getWeekdayText(weekday);
            $('#schedule-table-container').find("tr:gt(0)").each((index, row2) => {
                const lessonText = $(row2).find("input[name=oindex]").attr("value");
                const option = $('<option>');
                option.val(`${weekdayText} ${lessonText}节`);
                option.text(`${weekdayText} ${lessonText}节`);
                if (row && row.disable_week_time && row.disable_week_time.includes(`${weekdayText} ${lessonText}节`)) {
                    option.attr("selected", "selected");
                }
                options.push(option);
            });
        }
    });
    if ($('#DisableWeekTime').length > 0) {
        addOptionsToSelect(disableWeekTime, options);
    }
}

// 监听 weekday 和 daytime 复选框的变化
weekdaysCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', initDisableWeekRange);
    checkbox.addEventListener('change', initDisableWeekTime);
});
daytimeCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', initDisableWeekRange);
    checkbox.addEventListener('change', initDisableWeekTime);
});

// 监听 schedule-table-container 中的行变化
scheduleTableRows.on('DOMSubtreeModified', initDisableWeekTime);

// 初始化 DisableWeekRange 和 DisableWeekTime 下拉列表
setTimeout(initDisableWeekRange, 500);
setTimeout(initDisableWeekTime, 1500);


$(document).on("change change2", "#c-table_id", function (e) {
    that=$(this);
    if (e.type == "change2") {
        $.ajax({
            url: "/coursetable/coursetable/lists?XDEBUG_SESSION_START=54354",
            data: {
                cityId: Config.admin['city_id'],
                school_id: $("#c-school_id").val(),
                community_id: $("#c-community_id").val(),
                addresslv_id: $("#c-address_lv").val()
            },
            type: "GET",
            success: function (data) {
                var $school = $("#c-table_id");
                $school.empty();
                var list = JSON.parse(data);
                $.each(list["list"], function (index, school) {
                    $school.append('<option value="' + school.id + '">' + school.name + '</option>');
                });
                if (row) {
                    that.val(row.table_id);
                } else if (that.find("option").length == 2) {
                    that.find("option").each(function () {
                        var value = $(this).val();
                        if (value !== "" && value !== "0") {
                            $(this).prop("selected", true);
                            return false;
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching school list: ", error);
            }
        });
    } else {

    }
});


if ($('#c-latitude').length > 0) {
    var map = new BMap.Map("map");
    map.enableScrollWheelZoom(true);
    var districtCoordinates = {
        "广西壮族自治区": {
            "南宁市": {
                "": new BMap.Point(108.35528924434603, 22.829188250573992),
                "市级": new BMap.Point(108.35528924434603, 22.829188250573992),
                "青秀区": new BMap.Point(108.35528924434603, 22.829188250573992),
                "兴宁区": new BMap.Point(108.3313, 22.8404),
                "西乡塘区": new BMap.Point(108.2729, 22.8567),
                "江南区": new BMap.Point(108.2833, 22.8087),
                "武鸣区": new BMap.Point(108.2807, 23.1636),
                "良庆区": new BMap.Point(108.3774, 22.7833),
                "邕宁区": new BMap.Point(108.4659, 22.7507),
                "隆安县": new BMap.Point(107.703, 23.1708),
                "马山县": new BMap.Point(108.2034, 23.7233),
                "上林县": new BMap.Point(108.5657, 23.4652),
                "宾阳县": new BMap.Point(108.8093, 23.2219),
                "横县": new BMap.Point(109.2054, 22.6848)
            },
            "柳州市": {
                "": new BMap.Point(109.4153, 24.3136),
                "城中区": new BMap.Point(109.4153, 24.3136),
                "鱼峰区": new BMap.Point(109.4336, 24.3329),
                "柳南区": new BMap.Point(109.4048, 24.3297),
                "柳北区": new BMap.Point(109.4528, 24.3556)
            },
            "桂林市": {
                "秀峰区": new BMap.Point(110.2875, 25.2797),
                "叠彩区": new BMap.Point(110.2822, 25.3055),
                "象山区": new BMap.Point(110.2857, 25.259),
                "七星区": new BMap.Point(110.3078, 25.2711)
            }
        }
    };

    $(document).on("dblclick blur", "#c-address", function () {
        var address = $(this).val();
        if (address) {
            geocoderSearch($("#city option:selected").text() + address);
        }
    });

    // 监听地图点击事件
    map.addEventListener("click", function (e) {
        var point = e.point;
        if (marker) {
            map.removeOverlay(marker);
        }
        map.clearOverlays(); // 清除之前的标注
        marker = new BMap.Marker(point);
        map.addOverlay(marker);
        $("#c-latitude").val(point.lat);
        $("#c-longitude").val(point.lng);
        getAddress(point);
    });

    // 初始更新
    updateMap(1);
}

$(document).ready(function () {
    // 获取select标签
    var allLocations = [];
    var selectElement = $('#c-classes_id');
    // 初始化allLocations数组


    // 生成表格的方法
    function generateTable() {
        allLocations = [];
        selectElement.find('option').each(function () {
            var location = {
                id: $(this).val(),
                name: $(this).text().trim(),
                level: parseInt($(this).attr('level')),
                parent: $(this).attr('parent')
            };
            allLocations.push(location);
        });

        // 获取选中的option的value
        var selectedLocations = selectElement.find('option:selected').map(function () {
            return $(this).val();
        }).get();

        // 过滤出选中的地点信息
        var filteredLocations = allLocations.filter(function (location) {
            return selectedLocations.includes(location.id);
        });

        // 生成表格
        var tableHtml = '<table class="table table-striped"><thead><tr><th>ID</th><th>三级地址</th><th>二级地址</th><th>一级地址</th><th>操作</th></tr></thead><tbody>';

        filteredLocations.forEach(function (location) {
            // 查找父级和父父级地址
            var parentLocation = allLocations.find(function (loc) {
                return loc.id === location.parent;
            });
            var grandparentLocation = allLocations.find(function (loc) {
                return loc.id === parentLocation.parent;
            });

            // 生成表格行
            tableHtml += '<tr><td>' + location.id + '</td><td>' + location.name + '</td><td>' + parentLocation.name + '</td><td>' + grandparentLocation.name + '</td><td><a href="#" class="btn btn-primary btn-xs">设置</a></td></tr>';
        });

        tableHtml += '</tbody></table>';

        // 将表格插入到页面中
        $('#table-container').html(tableHtml);
    }

    // 在select的change事件中调用生成表格的方法
    selectElement.change(function () {
        generateTable();
    });

    // 页面加载时生成初始表格
    generateTable();

});


if ($("#c-daytime-all").length > 0) {
    let daysOfWeek;
    let timePeriods;
    let options;
    let selectedOptions;
    disableWeekRangeSelect = document.getElementById('c-disable_week_range');
    mustWeekRange = document.getElementById('c-must_week_range');
    daytimeall = document.getElementById('c-daytime-all');
    daysOfWeek = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    timePeriods = ['上午', '中午', '下午', '晚上'];
    options = daysOfWeek.flatMap(day => {
        return timePeriods.map(period => {
            if (row && row.disable_week_range) {
                select = row.disable_week_range.split(",");
                if (select.includes(day + period)) {
                    return `<option value="${day}${period}" selected>${day}${period}</option>`;
                } else {
                    return `<option value="${day}${period}">${day}${period}</option>`;
                }
            } else {
                return `<option value="${day}${period}">${day}${period}</option>`;
            }
        });
    });
    daytimeall.innerHTML = options.join('');
    // 获取所有选中的选项
    selectOptions = Array.from(document.getElementById('c-daytime-all').options);
    $(document).on("change change2", "#c-daytime-all", function () {
        selectedOptions = Array.from(document.getElementById('c-daytime-all').selectedOptions);
        if (disableWeekRangeSelect) {
            disableWeekRangeSelect.innerHTML = ''; // 清空所有选项
            disableWeekRangeSelect.appendChild(new Option("不选择", ""));
            selectedOptions.forEach(option => {
                clonedOption3 = option.cloneNode(true);
                disableWeekRangeSelect.appendChild(clonedOption3);
            });
            disableWeekRangeSelect.addEventListener('change', function () {
                if (this.value === "") {
                    for (let i = 0; i < this.options.length; i++) {
                        if (this.options[i].value !== "") {
                            this.options[i].selected = false;
                        } else {
                            this.options[i].selected = true;
                        }
                    }
                }
            });
        }
        if (mustWeekRange) {
            mustWeekRange.innerHTML = ''; // 清空所有选项
            mustWeekRange.appendChild(new Option("不选择", ""));
            selectedOptions.forEach(option => {
                clonedOption4 = option.cloneNode(true);
                mustWeekRange.appendChild(clonedOption4);
            });
            mustWeekRange.addEventListener('change', function () {
                if (this.value === "") {
                    // 如果选择了“不选择”，则取消其他选项的选中状态
                    for (let i = 0; i < this.options.length; i++) {
                        if (this.options[i].value !== "") {
                            this.options[i].selected = false;
                        }
                    }
                }
            });
        }

        selectOptions.forEach(option => {
            clonedOption = option.cloneNode(true);
            mustWeekRange.appendChild(clonedOption);
            clonedOption2 = option.cloneNode(true);
            disableWeekRangeSelect.appendChild(clonedOption2);
        });
    });




    if (row&& $('#c-daytime-all').count>0) {
        select = row.daytimeall.split(",");
        $('#c-daytime-all option').prop('selected', false);
        daytimeall = document.getElementById('c-daytime-all');

        for (let i = 0; i < daytimeall.options.length; i++) {
            if (select.includes(daytimeall.options[i].value)) {
                daytimeall.options[i].selected = true;
            }
        }

        select1 = row.disable_week_range.split(",");
        $('#c-disable_week_range option').prop('selected', false);
        for (let i = 0; i < disableWeekRangeSelect.options.length; i++) {
            if (select1.includes(disableWeekRangeSelect.options[i].value)) {
                disableWeekRangeSelect.options[i].selected = true;
            }
        }

        $('#c-must_week_range option').prop('selected', false);
        select2 = row.must_week_range.split(",");
        for (let i = 0; i < mustWeekRange.options.length; i++) {
            if (select2.includes(mustWeekRange.options[i].value)) {
                mustWeekRange.options[i].selected = true;
            }
        }
    }


    if ($('input[name="row[daytime][]"]')) {
        // 监听复选框的点击事件
        $('input[name="row[daytime][]"]').click(function () {
            selectedOptions = Array.from(document.getElementById('c-daytime-all').selectedOptions);
            selectedOptions_m = Array.from(document.getElementById('c-must_week_range').selectedOptions);
            selectedOptions_d = Array.from(document.getElementById('c-disable_week_range').selectedOptions);

            // 获取选中的时段
            var selectedTime = $(this).val();

            // 获取下拉列表
            var select = $('#c-daytime-all');

            // 清空下拉列表
            select.empty();
            // 根据选中的时段生成选项
            $('input[name="row[daytime][]"]:checked').each(function () {
                var time = $(this).val();
                if (time == 1) {
                    select.append('<option value="周一上午">周一上午</option>');
                    select.append('<option value="周二上午">周二上午</option>');
                    select.append('<option value="周三上午">周三上午</option>');
                    select.append('<option value="周四上午">周四上午</option>');
                    select.append('<option value="周五上午">周五上午</option>');
                    select.append('<option value="周六上午">周六上午</option>');
                    select.append('<option value="周日上午">周日上午</option>');
                } else if (time == 3) {
                    select.append('<option value="周一下午">周一下午</option>');
                    select.append('<option value="周二下午">周二下午</option>');
                    select.append('<option value="周三下午">周三下午</option>');
                    select.append('<option value="周四下午">周四下午</option>');
                    select.append('<option value="周五下午">周五下午</option>');
                    select.append('<option value="周六下午">周六下午</option>');
                    select.append('<option value="周日下午">周日下午</option>');
                } else if (time == 4) {
                    select.append('<option value="周一晚上">周一晚上</option>');
                    select.append('<option value="周二晚上">周二晚上</option>');
                    select.append('<option value="周三晚上">周三晚上</option>');
                    select.append('<option value="周四晚上">周四晚上</option>');
                    select.append('<option value="周五晚上">周五晚上</option>');
                    select.append('<option value="周六晚上">周六晚上</option>');
                    select.append('<option value="周日晚上">周日晚上</option>');
                } else if (time == 2) {
                    select.append('<option value="周一中午">周一中午</option>');
                    select.append('<option value="周二中午">周二中午</option>');
                    select.append('<option value="周三中午">周三中午</option>');
                    select.append('<option value="周四中午">周四中午</option>');
                    select.append('<option value="周五中午">周五中午</option>');
                    select.append('<option value="周六中午">周六中午</option>');
                    select.append('<option value="周日中午">周日中午</option>');
                }
            });

            selectOptions = Array.from(document.getElementById('c-daytime-all').options);
            $(mustWeekRange).html("");
            $(disableWeekRangeSelect).html("");
            selectOptions.forEach(option => {
                clonedOption = option.cloneNode(true);
                mustWeekRange.appendChild(clonedOption);
                clonedOption2 = option.cloneNode(true);
                disableWeekRangeSelect.appendChild(clonedOption2);
            });
            select = selectedOptions.map(option => option.value);
            daytimeall = document.getElementById('c-daytime-all');
            for (let i = 0; i < daytimeall.options.length; i++) {
                if (select.includes(daytimeall.options[i].value)) {
                    daytimeall.options[i].selected = true;
                } else {
                    daytimeall.options[i].selected = false;
                }
            }

            select1 = selectedOptions_d.map(option => option.value);
            for (let i = 0; i < disableWeekRangeSelect.options.length; i++) {
                if (select1.includes(disableWeekRangeSelect.options[i].value)) {
                    disableWeekRangeSelect.options[i].selected = true;
                } else {
                    disableWeekRangeSelect.options[i].selected = false;
                }
            }

            select2 = selectedOptions_m.map(option => option.value);
            for (let i = 0; i < mustWeekRange.options.length; i++) {
                if (select2.includes(mustWeekRange.options[i].value)) {
                    mustWeekRange.options[i].selected = true;
                }
            }

        });
    }
}


$(document).on("click change load","#maxks,#c-classes-per-week,input[name='row[daytime][]'],input[name='row[weekdays][]'],select[name='row[disable_week_range][]'],.add-class,.remove-class,#DisableWeekTime,#DisableWeekRange",function(){
    sds=$("input[name='daytime']").length;
    zs=$("input[name='row[weekdays][]']:checked").length;
    jysds=$("#DisableWeekTime option:selected").length; //禁用时点数
    function timescount(targetChar) {
        var count2 = 0;  //检查上午有多少个？
        $("input[name=daytime]").each(function() {
            var value = $(this).val(); // 获取当前 input 的值
            if (value.includes(targetChar)) { // 检查值是否包含目标字符
                count2++; // 如果包含，则计数器加1
            }
        });
        return count2;
    }
    function hasweek(targetChar) {
        var result = false;  //检查是否有周一？
        $("input[name='row[weekdays][]']:checked").each(function() {
            var value = $(this).closest("label").html(); // 获取当前 input 的值
            if (value.includes(targetChar)) { // 检查值是否包含目标字符
                result=true;
                return false;
            }
        });
        return result;
    }

    jyzds=0;
    $("#DisableWeekRange option:selected").each(function(){
        ss=$(this).text();
        shangzxw=ss.match(/上|中|下|晚/g);
        week=ss.match(/一|二|三|四|五|六|日/g);
        if(hasweek(week[0])&&timescount(shangzxw[0])>0){
            jyzds+=timescount(shangzxw[0]);
        }
    });
    count=sds*zs-jysds-jyzds;
    $("#maxks").html(count);
    if($("#c-classes-per-week").val()>count){
        $("#c-classes-per-week").val(count);
    }
});
$(document).ready(function(){
    setTimeout(function() {
        $("#maxks").trigger("change");
    },2000);
});






$(".btn-switcher").click(function (event) {
    event.preventDefault();
    var isChecked = !$(this).find("i").hasClass("text-gray");
    $(this).closest("div").find("input").val(isChecked ? 0 : 1);
    if (isChecked) {
        $(this).find("i").addClass("text-gray");
    } else {
        $(this).find("i").removeClass("text-gray");
    }
});


$(document).on("mousedown", "#c-disable_week_range, #c-must_week_range, #c-daytime-all,.selects", function () {
    if (!event.ctrlKey) {
        event.preventDefault();
    }
});




if ($('#c-school_id').length > 0) {
    $("#c-school_id").trigger("change2");
}
if ($('#c-school_id_tree').length > 0) {
    $("#c-school_id_tree").trigger("change2");
}

if ($('select[name="row[community_id]"]').length > 0) {
    $("select[name='row[community_id]']").trigger("change2");
}

if ($('select[name="row[subject_lv]"]').length > 0) {
    $("select[name='row[subject_lv]']").trigger("change2");
}

if ($('#c-subject_lv2').length > 0) {
    $("#c-subject_lv2").trigger("change2");
}

if ($('#c-subject_lv3,#c-subjecct-lv3-pid').length > 0) {
    $("#c-subject_lv3,#c-subjecct-lv3-pid").trigger("change3");
}

if ($('#c-ocation_id').length > 0) {
    $('#c-ocation_id').trigger("change2");
}
if ($('#c-table_id').length > 0) {
    $('#c-table_id').trigger("change2");
}

if ($('#c-ocation_pid').length > 0) {
    $('#c-ocation_pid').trigger("change2");
}

if ($('#c-ocation_class').length > 0) {
    $('#c-ocation_class').trigger("change2");
}

if ($('#c-address_lv_octionlevel').length > 0) {
    $('#c-address_lv_octionlevel').trigger("change2");
}

if ($('#c-classes_id').length > 0) {
    $('#c-classes_id').trigger("change2");
}

if ($('#c-teacher_id').length > 0) {
    $('#c-teacher_id').trigger("change2");
}


if ($('#c-address_lv').length > 0) {
    $('#c-address_lv').trigger("change2");
}

if ($('#c-class_type').length > 0) {
    $('#c-class_type').trigger("change2");
}
if ($('#c-classes_type').length > 0) {
    $('#c-classes_type').trigger("change2");
}

if ($('#c-address_lv_pid').length > 0) {
    $('#c-address_lv_pid').trigger("change4");
}

if ($('#c-address_lv3,#c-addresslv_id3').length > 0) {
    $('#c-address_lv3,#c-addresslv_id3').trigger("change3");
}

//仅一二级地址可选
if ($('#c-address_lv4,#c-addresslv_id4').length > 0) {
    $('#c-address_lv4,#c-addresslv_id4').trigger("change4");
}

if ($('#c-rel_type').length > 0) {
    $('#c-rel_type').trigger("change3");
}

if ($('select[group]').length > 0) {
    $('select[group]').trigger("change3");
}